/** @format */

import React, {useState, useEffect} from 'react';
import {header} from './index.styl';
import {store} from '@/store';
import AudioPlayer from '@/components/audio_play';
import PlayArrow from '@material-ui/icons/PlayArrow';
import Pause from '@material-ui/icons/Pause';
import Menu from '@material-ui/icons/Menu';
import { yo } from 'yoo-hoo';

interface IAudioState {
  progress: number;
  duration: number;
  currentTime: number;
}

interface IState {
  progress: string;
  audioSrc: string;
  play: boolean;
  isBlogPage: boolean;
}

interface IProps {
  history: any;
}

const Header = () => {
  let lastAudio = '';
  const [data, setState] = useState({
    progress: '0',
    audioSrc: '',
    play: false,
    isBlogPage: false,
  });

  const getAudioState = (audioState: IAudioState) => {
    setState({...data, progress: `${audioState.progress}%`});
  };

  const toggleMenuShow = (): void => {
    store.dispatch({type: 'isStretch', val: !store.getState().isStretch});
  };

  const updateState = () => {
    const {audioSrc} = store.getState();

    if (audioSrc && audioSrc !== lastAudio) {
      const newData = {
        ...data,
        isBlogPage: location.href.indexOf('/post/') > -1,
      };

      lastAudio = audioSrc;
      newData.audioSrc = audioSrc;
      newData.progress = '0';

      setState({...newData});
    }
  };

  useEffect(() => {
    yo('HI');
    updateState();
    store.subscribe(() => {
      updateState();
    });
  }, []);

  return (
    <>
      <header className={header}>
        <div style={{width: data.progress}}>
          <Menu
            onClick={() => {
              toggleMenuShow();
            }}
          />
          {data.isBlogPage && data.audioSrc ? (
            data.play ? (
              <Pause
                onClick={() => {
                  setState({...data, play: false});
                }}
              />
            ) : (
              <PlayArrow
                onClick={() => {
                  setState({...data, play: true});
                }}
              />
            )
          ) : (
            ''
          )}
        </div>
      </header>
      <AudioPlayer
        src={data.audioSrc}
        play={data.play}
        getAudioState={(audioState: IAudioState) => getAudioState(audioState)}
      />
    </>
  );
};

export default Header;
